#!/bin/bash
# Copyright (c) 2020 maminjie <maminjie1@huawei.com>
# SPDX-License-Identifier: MulanPSL-2.0

repo=standard_aarch64
arch=aarch64
yumrepo="--repo mainline"               # change this for you

usage() {
    echo "Usage:"
    echo ""
    echo "script PROJECT PACKAGE        # Iterate to analyze the binary packages under the source package"
    echo "          |       |-----------  src package"
    echo "          |-------------------- obs project"
    echo ""
    echo "script PACKAGE                # Analyze the specified binary package"
    echo "          |-------------------- bin package (rpm sub-package)"
    echo ""
    echo "The script is used to analyze the dependency(RequiredBy/BuildRequiredBy) of the package"
}

# get_bin_pkgname(pkgs)
get_bin_pkgname() {
    for p in $1; do
        name=$(dnf info $p $yumrepo 2>/dev/null | grep "Name" | head -n 1 | awk '{print $3}')
        if [ -n "$name" ]; then
            echo "$name"
        else
            name=$(echo "$p" | sed 's/-[[:digit:]]\+.*//')
            echo "$name"
        fi
    done
}

# get_provides(pkg)
get_provides() {
    local pros=""
    pros=$(dnf repoquery --provides "$1" $yumrepo 2>/dev/null | sed 's/^(//' | sed 's/ \+.*//')
    echo "$pros"
}

# get_whatrequires(symbol)
get_whatrequires() {
    local bins=""
    bins=$(dnf repoquery --whatrequires "$1" $yumrepo 2>/dev/null | uniq)
    bins=$(get_bin_pkgname "$bins" | uniq)
    echo "$bins"
}

# get_bins_fromobs(prj, pkg)
get_bins_fromobs() {
    local bins=""
    # /build/project/repo/arch/package
    local content="/build/$1/$repo/$arch/$2"
    bins=$(osc api -X GET "$content" 2> /dev/null | grep ".rpm" | awk '{print $2}' | awk -F '=' '{print $2}' | sed 's/"//g' | sed 's/\.rpm$//g' | uniq)
    bins=$(get_bin_pkgname "$bins" | uniq)
    echo "$bins"
}

# get_source(bin)
get_source() {
    local src=""
    src=$(dnf repoquery -q -i "$1" $yumrepo | grep Source | grep -v "None" | head -n1 | awk '{print $3}' | sed 's/\.rpm$//g')
    src=$(get_bin_pkgname "$src" | uniq)
    echo "$src"
}

# get_bin_berequired(bin)
get_bin_berequired() {
    pros=$(get_provides "$1")
    for j in $pros; do
        rbins=$(get_whatrequires "$j")
        for k in $rbins; do
            rsrc=$(get_source "$k")
            if [ -n "$rsrc" ]; then
                echo "$rsrc"
            fi
        done
    done
}

# get_berequired(prj, pkg)
get_berequired() {
    local bins=$(get_bins_fromobs "$1" "$2")
    for i in $bins; do
        get_bin_berequired $i
    done
}

main() {
    if [ $# == 2 ]; then
        deps=$(get_berequired "$1" "$2" | sort | uniq)
    elif [ $# == 1 ]; then
        deps=$(get_bin_berequired "$1" | sort | uniq)
    else
        usage; exit
    fi

    if [ -n "$deps" ]; then
        echo "$deps"
    fi
}

main "$@"

